package com.l.web.util;

import com.l.web.WebConstant;
import com.l.web.master.system.user.User;
import org.apache.log4j.Logger;
import com.l.web.common.ResponseInfo;
import org.l.qiao.web.form.Form;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by 严秋旺 on 2015/4/23.
 */
public abstract class ControllerSupport implements ApplicationContextAware {

    private static final Logger LOGGER = Logger.getLogger(ControllerSupport.class);
    private ApplicationContext context;

    protected <T> T getBean(Class<T> clazz) {
        return context.getBean(clazz);
    }

    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.context = context;
    }

    protected User getLoginUser(HttpServletRequest request) {
        return (User) request.getSession().getAttribute(WebConstant.SESSION_USER);
    }

    protected Form getForm(HttpServletRequest request) {
        return new Form(request);
    }

    public boolean out(HttpServletResponse response, int code) {
        ResponseInfo responseInfo = new ResponseInfo(code);
        return out(response, responseInfo);
    }

    public boolean out(HttpServletResponse response, long code) {
        ResponseInfo responseInfo = new ResponseInfo(code);
        return out(response, responseInfo);
    }

    public boolean out(HttpServletResponse response, Object content) {

        try {
            PrintWriter writer = response.getWriter();
            writer.write(String.valueOf(content));
        } catch (IOException e) {
            LOGGER.info("获取页面输出句柄异常：" + e);
            return false;
        }

        return true;
    }

}
